如何使用FabricJS使多边形对象对拖放事件做出反应

您所在的位置:网站首页 fabricjs 自定义连线 如何使用FabricJS使多边形对象对拖放事件做出反应

如何使用FabricJS使多边形对象对拖放事件做出反应

2024-07-01 11:10| 来源: 网络整理| 查看: 265

如何使用FabricJS使多边形对象对拖放事件做出反应

我们可以通过创建一个fabric.Polygon的实例来创建一个Polygon对象。一个多边形对象可以被描述为由一组连接的直线段组成的任何封闭形状。由于它是FabricJS的基本元素之一,我们也可以通过应用角度、不透明度等属性轻松定制它。我们使用event:dragover和event:drop事件来使多边形对象对拖放事件作出反应。

语法 event:dragover event:drop 例1:显示对象如何对下降事件做出反应

让我们看看一个代码例子,当我们把一个 “h1 “元素放在一个添加到画布上的多边形对象上面时,找到记录的输出。我们已经创建了一个 “h1 “元素,并给它一个id = “drop-me”。此外,我们使用getElementById()方法来返回 “h1 “元素,并使用addEventListener()方法来监听下降事件。因此,当我们抓住 “h1 “元素并把它放到多边形对象上时,有关该事件的属性就会显示出来。

Displaying how the object reacts to drop event

You can drop the box on the object and open the console from the dev tools to see that the event name, subTargets and target are being shown

Drop me // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a polygon instance var polygon = new fabric.Polygon( [ { x: 0, y: 0 }, { x: 0, y: 150 }, { x: 150, y: 150 }, { x: 150, y: 0 }, ], { left: 100, top: 60, fill: "red", stroke: "blue", strokeWidth: 2, objectCaching: false, } ); // Adding it to the canvas canvas.add(polygon); // Initiating the observe function function observe(eventName) { canvas.getObjects().forEach(function (object) { object.on(eventName, function evt(x) { console.log("Drop event has been fired", x); }); }); } // Using addEventListener and listening for drop event document .getElementById("drop-me") .addEventListener("change", observe("drop")); 例2:显示对象如何对拖动事件作出反应

让我们看一个代码例子,找到当我们在添加到画布上的多边形对象上拖动 “h1 “元素时的记录的输出。当我们拖动一个对象而将其移动到不同的位置时,就会发生拖动事件。然而,当我们在另一个对象上拖动一个对象时,会发生拖动事件。在这里,当我们把 “h1 “元素拖到一个多边形对象上时,事件名称、目标和子目标将被记录在控制台中。

Displaying how the object reacts to dragover event

You can drag the box on the object and open the console from the dev tools to see that the event name, target and subTargets are being shown

Drag me // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a polygon instance var polygon = new fabric.Polygon( [ { x: 0, y: 0 }, { x: 0, y: 150 }, { x: 150, y: 150 }, { x: 150, y: 0 }, ], { left: 100, top: 60, fill: "red", stroke: "blue", strokeWidth: 2, } ); // Adding it to the canvas canvas.add(polygon); // Initiating the observe function function observe(eventName) { canvas.getObjects().forEach(function (object) { object.on(eventName, function evt(x) { console.log("Dragover event has been fired", x); }); }); } // Using addEventListener and listening for dragover event document .getElementById("drag-me") .addEventListener("change", observe("dragover")); 结论

在本教程中,我们用两个简单的例子来演示如何使用FabricJS使多边形对象对拖放事件做出反应。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3